<?php

namespace app\common\service\aliyun;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\common\service\ConfigService;

/**
 * 阿里云短信服务
 */
class AliyunSmsService
{
    private string $accessKeyId;
    private string $accessKeySecret;
    private string $signName;
    private string $templateCode;

    public function __construct()
    {
        $this->setConfig();
    }


    private function setConfig()
    {
        $keys = 'sms_access_key_id,sms_access_key_secret,sms_sign_name,sms_template_code';
        $ConfigService = new ConfigService();
        $config = $ConfigService->getSysConfigValueList($keys);
        if (empty($config)) {
            getResponseException('短信服务配置错误', [], 1, 'ERROR');
        }
        // 从配置中获取阿里云短信服务配置
        $this->accessKeyId = $config['sms_access_key_id'] ?? '';
        $this->accessKeySecret = $config['sms_access_key_secret'] ?? '';
        $this->signName = $config['sms_sign_name'] ?? '';
        $this->templateCode = $config['sms_template_code'] ?? '';
    }

    /**
     * 发送短信验证码
     * @param string $phone 手机号
     * @param string $code 验证码
     * @return array
     */
    public function sendSms(string $phone, string $code): array
    {
        // 初始化阿里云客户端
        AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessKeySecret)
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->scheme('https')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => 'cn-hangzhou',
                        'PhoneNumbers' => $phone,
                        'SignName' => $this->signName,
                        'TemplateCode' => $this->templateCode,
                        'TemplateParam' => json_encode(['code' => $code], JSON_UNESCAPED_UNICODE),
                    ],
                ])
                ->request();

            $response = $result->toArray();

            if ($response['Code'] === 'OK') {
                return [
                    'code' => 0,
                    'msg' => '短信发送成功'
                ];
            } else {
                return [
                    'code' => -1,
                    'msg' => $response['Message'] ?? '短信发送失败'
                ];
            }
        } catch (ClientException|ServerException $e) {
            return [
                'code' => -1,
                'msg' => $e->getMessage()
            ];
        }
    }
}
